package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.tcc.OrderTccAction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    OrderTccAction orderTccAction;

    @GlobalTransactional//启动全局事务
    @Override
    public void create(Order order) {
        // 远程调用全局唯一ID发号器，生成订单id
        Long id = Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(id);
//        orderMapper.create(order);//不直接执行业务数据处理，而是手动调用TCC第一阶段方法
        //orderTccAction是一个动态代理对象，使用AOP添加了前置Advice，
        //在Advice中创建上下文对象，传入代理的目标方法中
        orderTccAction.prepare(null,
                id,
                order.getUserId(),
                order.getProductId(),
                order.getCount(),
                order.getMoney());


        // 远程调用库存，减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 远程调用账户，扣减账户金额
        accountClient.decrease(order.getUserId(),order.getMoney());
    }
}
